/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.wiki.plugins.impl;

import foo.bar.wiki.domain.User;
import foo.bar.wiki.domain.Role;
import foo.bar.wiki.plugins.UserRegistrationPlugin;
import foo.bar.wiki.services.UserService;
import foo.bar.wiki.security.RoleType;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.SimpleError;

import java.util.List;
import java.util.ArrayList;

/**
 * The default implementation of {@link foo.bar.wiki.plugins.UserRegistrationPlugin}.
 * <p/>
 * Whenever a {@link User} is registered it automatically enabled it.
 * <p/>
 * An alternative implementation would be to send out an activation email to the
 * {@link foo.bar.wiki.domain.User}'s email address that requires user interaction
 * before activating the account.
 *
 * @See {@link UserRegistrationPlugin}
 *
 * @author tmjee
 * @version $Date: 2009-03-14 14:53:07 +0800 (Sat, 14 Mar 2009) $ $Id$
 */
public class AutomaticallyEnabledUserRegistration extends AbstractPlugin implements UserRegistrationPlugin {



    protected UserService getUserService() {
        return getPluginContext().getUserService();
    }

    public void validate(User user, ValidationErrors validationErrors, List<Message> messages) {
        if (getUserService().isUsernameExists(user.getUsername())) {
            validationErrors.add("user.username", new SimpleError("User with username ["+user.getUsername()+"] already exists"));
        }
    }

    public void register(final User user, List<Message> messages) {
        user.setRoles(new ArrayList<Role>() {
            {
                Role r1 = new Role();
                r1.setOwner(user);
                r1.setType(RoleType.REGISTERED_USER);
                Role r2 = new Role();
                r2.setType(RoleType.MODERATOR);
                r2.setOwner(user);
                add(r1);
                add(r2);
            }
        });
        getUserService().saveOrUpdateUser(user);
        messages.add(new SimpleMessage("User with username ["+user.getUsername()+"] registered successfully"));
    }
}
